import { Card, Dropdown, Menu, Button, Modal } from "antd";
import { useState } from "react";

import { useDocumentTitle } from "utils/common";
import { Row as MyRow } from "components/lib";
import { CreateSearch } from "./create-search";
import { useSearch, useHotsSearchParams, useHotDel } from "./utils";
import { Search as Hot } from "types/search";
import { SearchPanel } from "./search-panel";
import { useDebounce } from "utils";

export const Hots = () => {
  useDocumentTitle("热门搜索");
  const [createSearch, setCreateSearch] = useState(false);
  const [param, setParam] = useHotsSearchParams();
  const { data: hots } = useSearch(useDebounce(param, 200));
  const startAdd = () => {
    setParam({ id: "", name: "" });
    setCreateSearch(true);
  };
  const close = () => {
    setParam({ id: "", name: "" });
    setCreateSearch(false);
  };

  return (
    <Card>
      <MyRow between={true} marginBottom={2}>
        <SearchPanel param={param} setParam={setParam} />
        <Button onClick={() => startAdd()} type={"link"}>
          添加搜索
        </Button>
      </MyRow>
      {hots?.map((hot) => (
        <MyRow
          key={hot.id}
          between={true}
          marginBottom={2}
          style={{ borderBottom: ".1rem solid #eee", lineHeight: "3rem" }}
        >
          <h3>{hot.name}</h3>
          <More hot={hot} setCreateSearch={setCreateSearch} />
        </MyRow>
      ))}
      <CreateSearch onClose={() => close()} visible={createSearch} />
    </Card>
  );
};

const More = ({
  hot,
  setCreateSearch,
}: {
  hot: Hot;
  setCreateSearch: (param: boolean) => void;
}) => {
  const { mutateAsync } = useHotDel();
  const startDel = () => {
    Modal.confirm({
      okText: "确定",
      cancelText: "取消",
      title: "确定删除吗?",
      onOk() {
        return mutateAsync({ id: hot.id });
      },
    });
  };
  const [param, setParam] = useHotsSearchParams();

  const startEdit = () => {
    setCreateSearch(true);
    setParam({
      ...param,
      id: hot.id,
    });
  };

  const overlay = (
    <Menu>
      <Menu.Item key={"del"}>
        <Button type={"link"} onClick={startDel}>
          删除
        </Button>
      </Menu.Item>
      <Menu.Item key={"edit"}>
        <Button type={"link"} onClick={startEdit}>
          编辑
        </Button>
      </Menu.Item>
    </Menu>
  );

  return (
    <Dropdown overlay={overlay}>
      <Button type={"link"}>...</Button>
    </Dropdown>
  );
};
